package com.health.mapp.impl;

import java.math.BigDecimal;
import java.util.Date;

import com.health.db.dto.StuffDetailDto;
import com.health.db.model.GoodsPriceList;
import com.health.db.model.GoodsPriceListTemp;
import com.health.db.model.RegisterOrder;
import com.health.db.model.UserAccountLedger;
import com.health.db.model.UserLIST;
import com.health.db.service.order.IRegisterOrderService;
import com.health.db.service.sm.IRongService;
import com.health.db.service.user.IGoodsPriceListService;
import com.health.db.service.user.IStuffListService;
import com.health.db.service.user.IUserAccountLedgerService;
import com.health.db.service.user.IUserLISTService;
import com.health.mapp.bean.Header;
import com.health.mapp.bean.ReceiveOrderReq;
import com.health.mapp.bean.ReceiveOrderResp;
import com.health.mapp.utils.Constant;
import com.health.mapp.utils.DateUtils;
import com.health.mapp.utils.Response;
import com.health.mapp.utils.ResultCode;

/**
 *  接受订单类
 *  此接口提供医生操作
 *  用户支付完成后，医生需要做订单确认操作(医生确认完成后，用户可以进行咨询操作)
 *  订单确认后，订单状态由等待就诊修改为就诊中
 *  此接口类似于淘宝中卖家点击发货按钮，订单处于卖家已发货状态
 * 注：缺少融云消息推送
 * @author HiRoad
 * 
 * @pramati
 * 	private Long  orderId; //订单号
	private Long patId ;//	String(Long)	Y	就诊人ID
	private Long  docId;//医生Id

 *
 */
public class ReceiveOrderImpl implements ActionInterface {
	
	//service import
	private IRegisterOrderService registerOrderService  ;
	private IUserLISTService userLISTService  ;
	private IGoodsPriceListService goodsPriceListService  ;
	private IUserAccountLedgerService userAccountLedgerService  ;
    private IStuffListService stuffListService  ;
	
	private IRongService rongService  ; 
	
	@Override
	public Response execute(Header header, Object reqBean) throws Exception {
		
		ReceiveOrderReq req = (ReceiveOrderReq) reqBean; 
		ReceiveOrderResp _resp = new ReceiveOrderResp();
		Long orderId = req.getOrderId();
		Long docId =req.getDocId();
		//type不再需要，此类只做医生对订单进行接受操作
		int type = req.getType();
		
		if (type==-1||docId==0||orderId==0) {
			_resp.setErrorCode(ResultCode.OPERATION_LAKE_PARAMETER_ERROR);
			_resp.setErrorMsg(ResultCode.OPERATION_LAKE_PARAMETER_ERROR_NOTE);
			return _resp;
		}else{
		 
			 //获取当前要处理的订单
			RegisterOrder  currRegisterOrder =registerOrderService.selectSimpleSingleByOrderId(orderId);
			
			if (type==3) {
				return quitOrder(_resp, currRegisterOrder);
			}
			
			//判断订单状态
			if (currRegisterOrder==null) {
				_resp.setErrorCode(ResultCode.OPERATION_ORDER_ERROR_3001);
				_resp.setErrorMsg(ResultCode.OPERATION_ORDER_ERROR_3001_NOTE);
				return _resp;
			}
			int runStatusId=currRegisterOrder.getRunstatusid().intValue();
			int freeType=currRegisterOrder.getOrderfeetypeid().intValue();
			
			//医生校验
			int channel = Integer.valueOf(currRegisterOrder.getRegisterguideid());
			if ((freeType!=0)&&(channel!=Constant.CONSTANTS_ORDER_CHANNEL_ID_7.intValue())
						&&(currRegisterOrder.getAccepterid().longValue()!=docId)) {
				_resp.setErrorCode(ResultCode.OPERATION_ORDER_ERROR_3001);
				_resp.setErrorMsg("本订单入参医生无权接受");
				return _resp;
			}else if (null ==currRegisterOrder.getAccepterid()||currRegisterOrder.getAccepterid() ==0){
				
				currRegisterOrder.setAccepterid(docId);
			}
			
			StuffDetailDto stuffDetailDto = stuffListService.selectByStuffId(docId);
			
			if (null!=stuffDetailDto&&stuffDetailDto.getRegisterWhere().contains(currRegisterOrder.getRegisterguideid())) {
				
			}else{
				_resp.setErrorCode(ResultCode.OPERATION_ORDER_ERROR_3001);
				_resp.setErrorMsg("本订单入参医生无权接受");
				return _resp;
			}
			
			//完成订单时，订单是状态不能是就诊中
			if ((type==2)&&runStatusId!=Constant.CONSTANTS_ORDER_RUNSTATUS_ID_3.intValue()) {
				_resp.setErrorCode(ResultCode.OPERATION_ORDER_ERROR_3003);
				_resp.setErrorMsg(ResultCode.OPERATION_ORDER_ERROR_3003_NOTE);
				
				return _resp;
			}
			
			if ((type==1)&&runStatusId!=Constant.CONSTANTS_ORDER_RUNSTATUS_ID_2.intValue()) {
				
				if (Constant.CONSTANTS_COMMON_ORDER.contains(currRegisterOrder.getRegisterguideid())
						&&docId.longValue()!=currRegisterOrder.getAccepterid().longValue()) {
					_resp.setErrorCode(ResultCode.OPERATION_ORDER_ERROR_3013);
					_resp.setErrorMsg(ResultCode.OPERATION_ORDER_ERROR_3013_NOTE);
					return _resp;
				}else{
					_resp.setErrorCode(ResultCode.OPERATION_ORDER_ERROR_3014);
					_resp.setErrorMsg(ResultCode.OPERATION_ORDER_ERROR_3014_NOTE);
					return _resp;
				}
			}
			
			//免费的图文咨询订单在接受时,订单价格也需要填写到订单信息中
			//1,4,7
			//CONSTANTS_COMMON_ORDER 抢单订单
			if (Constant.CONSTANTS_COMMON_ORDER.contains(currRegisterOrder.getRegisterguideid()))
			{
				
				GoodsPriceList example = new GoodsPriceList();
				example.setSerialIdno(req.getDocId().toString());
				example.setGoodsid(currRegisterOrder.getGoodsid().intValue());
				//查询医生的单体价格
				GoodsPriceListTemp goodsPriceList =goodsPriceListService.selectByGoodsIdDocId(example);
				
				if (null == goodsPriceList) {
					_resp.setErrorCode(ResultCode.OPERATION_ORDER_ERROR_3001);
					_resp.setErrorMsg("本订单入参医生无权接受");
					return _resp;
				}
			
				currRegisterOrder.setDepartmentid(stuffDetailDto.getDepartmentid());
				currRegisterOrder.setDepartmentName(stuffDetailDto.getDepartmentName());
				currRegisterOrder.setAccepterName(stuffDetailDto.getStuffName());
				currRegisterOrder.setRegisterPayoffTotal(new BigDecimal (goodsPriceList.getPrice00()));
				currRegisterOrder.setEntityid(stuffDetailDto.getEntityid());
			}
			
			//医生的账户
			UserAccountLedger accountLedge = new UserAccountLedger();
			if(type==1){
				
				//接受时，修改为就诊中状态
				//actionMethod =Constant.CONSTANTS_ORDER_ACTION_ID_3;
				currRegisterOrder.setRunStatus(Constant.CONSTANTS_ORDER_RUNSTATUS_DES_3);
				currRegisterOrder.setRunstatusid(Constant.CONSTANTS_ORDER_RUNSTATUS_ID_3);
				Date currDateTime=DateUtils.getDatetime();
				currRegisterOrder.setAcceptTime(currDateTime);
		       
				currRegisterOrder.setUpdateDate(currDateTime);
				
				//接受订单，只更新订单表,并记录日志
				int returnFlag = registerOrderService.updateOrder4Accept(currRegisterOrder);
				//融云 操作
				if (returnFlag==1) {
					String[] userIds = {String.valueOf(docId)};
					//String[] toUserId = {String.valueOf(currRegisterOrder.getUserid())};
					String groupId = String.valueOf(orderId);
					//加入群组
					rongService.joinGroup(userIds, groupId, groupId);
					//向用户推送消息
					rongService.PublishSystemOrderToUserMsg(currRegisterOrder);
				}else if(returnFlag==-2){
					_resp.setErrorCode(ResultCode.OPERATION_ORDER_ERROR_3013);
					_resp.setErrorMsg(ResultCode.OPERATION_ORDER_ERROR_3013_NOTE);
					return _resp;
				}else {
					_resp.setErrorCode(ResultCode.OPERATION_ORDER_ERROR_3013);
					_resp.setErrorMsg(ResultCode.OPERATION_ORDER_ERROR_3013_NOTE);
					return _resp;
				}
			 }else if (type==2) {
				 
				//关闭时，修改为等待评价
				//Constant.CONSTANTS_ORDER_ACTION_ID_4;
				currRegisterOrder.setRunStatus(Constant.CONSTANTS_ORDER_RUNSTATUS_DES_4);
				currRegisterOrder.setRunstatusid(Constant.CONSTANTS_ORDER_RUNSTATUS_ID_4);
				
				
				//三个小时之内的订单不可以关闭
				Date updateDate=currRegisterOrder.getUpdateDate();
				Date currDate=DateUtils.now();
				if(DateUtils.judgmentDate(updateDate, currDate,3))
				{
					_resp.setErrorCode(ResultCode.OPERATION_ORDER_ERROR_3027);
					_resp.setErrorMsg(ResultCode.OPERATION_ORDER_ERROR_3027_NOTE);
					return _resp;
				}
				
				//医生账户表
				//关闭时，医生账户里获得相应的订单金额
				//分类账户更新数据
				accountLedge = userAccountLedgerService.selectByUserId(docId);
				int accountType=0;
				//如果医生应得到的为0 不做插入日志处理
				if (currRegisterOrder.getRegisterPayoffTotal().compareTo(new BigDecimal(0))>0) {
					
					if (null!=accountLedge&&accountLedge.getAcctpageid().intValue()!=0) {
						accountType=1;
						//医生获得的补偿累加
						accountLedge.setBalanceTotal(accountLedge.getBalanceTotal().add(currRegisterOrder.getRegisterPayoffTotal()));
					}else{
						
						accountLedge = new UserAccountLedger();
						accountLedge.setBalanceTotal(currRegisterOrder.getRegisterPayoffTotal());
						accountLedge.setAccountid(docId);
						accountLedge.setIsUsedFlag((short) 1);
						accountLedge.setColumnid(1);
					}
					//更新订单表，更新账户表
					registerOrderService.updateOrder4Finish(currRegisterOrder, accountLedge, accountType);
				}else{
					registerOrderService.updateOrder4Finish(currRegisterOrder);
				}
				 
				String userId = String.valueOf(docId);
				String[] toUserId = {String.valueOf(currRegisterOrder.getUserid())};
				String groupId = String.valueOf(orderId);
				//rongService.dismissGroup(userId, groupId);
				//向用户发送
				rongService.PublishSystemCloseOrderMsg(groupId, userId, toUserId);
			}else{
				
				_resp.setErrorCode(ResultCode.OPERATION_ORDER_ERROR_3004);
				_resp.setErrorMsg(ResultCode.OPERATION_ORDER_ERROR_3004_NOTE);
				return _resp;
			}
		}
		
		_resp.setErrorCode(ResultCode.OPERATION_SUCCESS);
		_resp.setErrorMsg(ResultCode.OPERATION_SUCCESS_NOTE);
 
		return _resp;
	}
	
	
	//退单 退群组
	private ReceiveOrderResp quitOrder(ReceiveOrderResp _resp ,RegisterOrder  currRegisterOrder ){
		int runStatusId=currRegisterOrder.getRunstatusid().intValue();
		//完成订单时，订单是状态不能是就诊中
		if (runStatusId!=Constant.CONSTANTS_ORDER_RUNSTATUS_ID_3.intValue()) {
			_resp.setErrorCode(ResultCode.OPERATION_ORDER_ERROR_3028);
			_resp.setErrorMsg(ResultCode.OPERATION_ORDER_ERROR_3028_NOTE);
			
			return _resp;
		}else{
			
			//视屏咨询
			if (currRegisterOrder.getRegistertypeid().intValue()!=Constant.CONSTANTS_ORDER_TYPE_ID_1.intValue()) {
				_resp.setErrorCode(ResultCode.OPERATION_ORDER_ERROR_3029);
				_resp.setErrorMsg(ResultCode.OPERATION_ORDER_ERROR_3029_NOTE);
				
				return _resp;
			}
			
			currRegisterOrder.setRunStatus(Constant.CONSTANTS_ORDER_RUNSTATUS_DES_2);
			currRegisterOrder.setRunstatusid(Constant.CONSTANTS_ORDER_RUNSTATUS_ID_2);
			currRegisterOrder.setRegisterguideid(String.valueOf(Constant.CONSTANTS_ORDER_CHANNEL_ID_7));
			
			//接受订单，只更新订单表,并记录日志
			int returnFlag = registerOrderService.updateOrder4Quit(currRegisterOrder);
			//融云 操作
			if (returnFlag==1) {
				String[] userIds = {String.valueOf(currRegisterOrder.getAccepterid())};
				//String[] toUserId = {String.valueOf(currRegisterOrder.getUserid())};
				String groupId = String.valueOf(currRegisterOrder.getRegisterid());
				//加入群组
				rongService.quitGroup(userIds, groupId);
				rongService.PublishSystemOrderToDocMsg(currRegisterOrder);
			}
			return _resp;
		}
	}

	public IRegisterOrderService getRegisterOrderService() {
		return registerOrderService;
	}

	public void setRegisterOrderService(IRegisterOrderService registerOrderService) {
		this.registerOrderService = registerOrderService;
	}

	public IUserLISTService getUserLISTService() {
		return userLISTService;
	}

	public void setUserLISTService(IUserLISTService userLISTService) {
		this.userLISTService = userLISTService;
	}

	public IGoodsPriceListService getGoodsPriceListService() {
		return goodsPriceListService;
	}

	public void setGoodsPriceListService(
			IGoodsPriceListService goodsPriceListService) {
		this.goodsPriceListService = goodsPriceListService;
	}

	public IUserAccountLedgerService getUserAccountLedgerService() {
		return userAccountLedgerService;
	}

	public void setUserAccountLedgerService(
			IUserAccountLedgerService userAccountLedgerService) {
		this.userAccountLedgerService = userAccountLedgerService;
	}

	/**
	 * @return the rongService
	 */
	public IRongService getRongService() {
		return rongService;
	}

	/**
	 * @param rongService the rongService to set
	 */
	public void setRongService(IRongService rongService) {
		this.rongService = rongService;
	}

	/**
	 * @return the stuffListService
	 */
	public IStuffListService getStuffListService() {
		return stuffListService;
	}

	/**
	 * @param stuffListService the stuffListService to set
	 */
	public void setStuffListService(IStuffListService stuffListService) {
		this.stuffListService = stuffListService;
	}
	
}
